package com.scs.application.modules.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.base.dto.SpChangeNameDTO;
import com.scs.application.modules.base.entity.Matr;
import com.scs.application.modules.base.entity.Supplier;
import com.scs.application.modules.base.mapper.SupplierMapper;
import com.scs.application.modules.base.service.MatrService;
import com.scs.application.modules.base.service.SupplierService;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import com.scs.application.modules.wm.entity.Stock;
import com.scs.application.modules.wm.entity.WorkOrderItem;
import com.scs.application.modules.wm.service.StockService;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/base/supplier")
public class SupplierController extends CrudController<SupplierService, Supplier> {
    @Autowired
    StockService stockService;
    @Autowired
    MatrService matrService;
    @Resource
    @Lazy
    SupplierMapper supplierMapper;

    /**
     * 删除数据
     */
    @DeleteMapping("/delete")
    public RestResult deleteItems(@RequestBody Map<String, Object> para) {
        List<Serializable> ids = (List<Serializable>) para.get("ids");

        List<String> spIds = service.list(Wrappers.<Supplier>query().in("id", ids)).stream().map(Supplier::getId).collect(Collectors.toList());
        if (spIds != null && spIds.size() > 0) {
            if (stockService.count(Wrappers.<Stock>query().in("supplier_id", spIds)) > 0)
                throw new BusinessException("该供应商已有库存记录，不允许删除");
            if (matrService.count(Wrappers.<Matr>query().in("supplier_id", spIds)) > 0)
                throw new BusinessException("该供应商已有耗材记录，不允许删除");
        }

        Boolean isOk = service.removeCascadeByIds(ids);
        if (!isOk) {
            return RestResult.error("数据删除失败");
        }
        return RestResult.ok("数据删除成功");
    }

    @Override
    public void fillDataForWeb(Supplier entity) {
        Boolean flagDisabledSpEdit = StringUtils.isNotBlank(entity.getMscmCode())
                || matrService.count(Wrappers.<Matr>query().eq("supplier_id", entity.getId())) > 0
                ;
        entity.setFlagDisabledSpEdit(flagDisabledSpEdit);
    }

    /**
     * 添加/更新数据
     */
    @PostMapping("/save")
    public RestResult saveItem(@Valid @RequestBody Supplier entity) {
        if (!entity.isNewRecord()) {
            Supplier entityDb = service.getById(entity.getId());
            if (!entity.getName().equals(entityDb.getName())
            ) {
                if (StringUtils.isNotBlank(entityDb.getMscmCode())) {
                    return RestResult.error("供应商已做了外网对照，不可更改名称");
                }
                if (matrService.count(Wrappers.<Matr>query().eq("supplier_id", entityDb.getId())) > 0) {
                    return RestResult.error("供应商已存在相关商品，不可更改名称");
                }
            }
        }

        boolean isOk = service.saveOrUpdate(entity);
        if (!isOk) {
            return RestResult.error("数据保存失败");
        }
        return RestResult.ok("数据保存成功", entity);
    }

    /**
     * 选择 获取数据列表
     */
    @GetMapping("/pageForSelect")
    public PageResult pageForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam = null;
        //固定参数
        if (reqData.containsKey("userParam")) {
            JSONObject ob = JSON.parseObject(reqData.get("userParam") + "");
            userParam = Maps.newHashMap(ob);
        }
        IPage pageResult = service.pageForSelect(queryContext, userParam);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }

    /**
     * 选择 获取数据列表
     */
    @GetMapping("/listForSelect")
    public RestResult listForSelect(@RequestParam Map<String, Object> reqData) {
        QueryContext queryContext = QueryContextHolder.currentContext();
        Map<String, Object> userParam = null;
        //固定参数
        if (reqData.containsKey("userParam")) {
            JSONObject ob = JSON.parseObject(reqData.get("userParam") + "");
            userParam = Maps.newHashMap(ob);
        }
        return RestResult.ok("查询成功", supplierMapper.listForSelect(queryContext.getWrapper(), queryContext.getParams(),userParam));
    }


    /**
     * 供应商更名
     */
    @PostMapping("/changeName")
    public RestResult changeName(@Valid @RequestBody SpChangeNameDTO changeParam) {
        return RestResult.ok(service.changeName(changeParam));
    }

}
